import sys
sys.setrecursionlimit(1000000) #例如这里设置为一百万
import os,json
from collections import defaultdict

# print('source:',source)

global new_list
new_list = ''
def update_list(source):
    global new_list

    repeat_location = []

    # 获取重复元素的位置
    def list_duplicates(source):
        seq =[]
        for i in range(len(source)):
            seq.append(int(source[i].split('_')[0]))
        tally = defaultdict(list)
        for i, item in enumerate(seq):
            tally[item].append(i)
        return ((key) for key, locs in tally.items()
                if len(locs) > 1)
    # index =
    for dup in sorted(list_duplicates(source)):
        repeat_location.append(dup)
    # print(len(repeat_location), repeat_location)

    for i in range(len(repeat_location)):
        locate = repeat_location[0] + 1
        new_l_before = source[:locate]
        new_l = source[locate:]
        for j in range(len(new_l)):
            loc = len(new_l[j].split('_')[0])
            new_l[j] =str(int(new_l[j].split('_')[0]) + 1)+new_l[j][loc:]
        seq = new_l_before + new_l
        new_list = seq
        update_list(new_list)
        # print('new list   ', new_list)
        return new_list

class order_case:
    def __init__(self,dir):
        self.dir =  dir

    def get_filepath(self):
        files_path = []
        for root, dirs, files in os.walk(self.dir):
            for i in range(len(files)):
                filepath = root + '\\' + files[i]
                files_path.append(filepath)
        return files_path

    # 将字母替换成数字
    def replace_index(self,order_filename):
        files_path=order_case.get_filepath(self)
        for i in range(len(order_filename)):
            for j in range(len(files_path)):
                filename = files_path[j].split('\\')[-1]
                f_index = filename.split('_')[0]
                start = len(f_index)
                end = len(filename)
                # print(start)
                real_filename = filename[start:end]
                path = os.path.dirname(files_path[j])

                if order_filename[i] == filename:
                    # print(filename, order_filename[i],real_filename)
                    old_path = path + "\\" + filename
                    new_path = path + "\\" + str(i) + real_filename
                    if old_path != new_path:
                        os.rename(path + "\\" + filename, path + "\\" + str(i) + real_filename)

    # 根据新顺序，修改文件名
    def replace_index_byOrder(self, order_filename):
        files_path = order_case.get_filepath(self)
        # print(order_filename)
        if order_filename != None:
            for i in range(len(order_filename)):
                order_index = order_filename[i].split('_')[0]
                real_order_start = len(order_index)
                real_order_end = len(order_filename)
                real_order_filename = order_filename[i][real_order_start:real_order_end]
                # print(real_order_filename)
                for j in range(len(files_path)):
                    filename = files_path[j].split('\\')[-1]
                    f_index = filename.split('_')[0]
                    start = len(f_index)
                    end = len(filename)
                    # print(start)
                    real_filename = filename[start:end]
                    # print(real_filename)
                    path = os.path.dirname(files_path[j])

                    if order_filename[i] != filename and real_order_filename == real_filename:
                        # print(filename, order_filename[i],real_filename)
                        old_path = path + "\\" + filename
                        new_path = path + "\\" + order_filename[i]
                        print('old path', old_path)
                        print('new path', new_path)
                        if old_path != new_path:
                            try:
                                os.rename(path + "\\" + filename, path + "\\" + order_filename[i])
                            except FileExistsError:
                                try:
                                    os.rename(path + "\\" + filename,
                                              path + "\\" + order_filename[i].split('.')[0] + str(i) + '.json')
                                except FileExistsError as e:
                                    print(e)
                                    print('file named similar,suggest change anothor name')


    # 获取根目录下的所有文件
    def get_allFile_order(self,type):
        filesList = []
        for root, dirs, files in os.walk(self.dir):
            # print(files)
            if files != []:
                for i in range(len(files)):
                    filesList.append(files[i])
        if type == 'letter':
            filesList = sorted(filesList)
        elif type == 'num':
            # print(filesList)
            filesList = sorted(filesList, key=lambda filesList: int(filesList.split('_')[0]))
        return filesList


    # 数字排序

    def get_new_name_json(self,filepath, value):
        with open(filepath, 'rb') as f:
            json_data = json.load(f)
            cfgdata = json_data[0]['config']['name']
            print('old_name', cfgdata)
            json_data[0]['config']['name'] = value
            print('new_name', json_data[0]['config']['name'])
        f.close()
        return json_data

    def rewrite_json_file(self,filepath, json_data):
        with open(filepath, 'w') as f:
            json.dump(json_data, f, sort_keys=True, indent=4, separators=(',', ':'))
        f.close()

    def get_cfg_name(self,filepath):
        with open(filepath, 'rb') as f:
            json_data = json.load(f)
            cfg_name = json_data[0]['config']['name']
        f.close()
        return cfg_name

    # 修改文件名和cfg name 的值一致
    def rename_file(self):
        for (path, dirs, files) in os.walk(self.dir):
            for filename in files:
                filepath = path + '\\' + filename
                with open(filepath, 'rb') as f:
                    json_data = json.load(f)
                    cfg_name = json_data[0]['config']['name']
                f.close()
                new_name = cfg_name+'.json'
                if new_name != filename:
                    print(new_name,filename)
                    os.rename(path + "\\" + filename, path + "\\" + new_name)

    #修改cfg name 和 文件名保持一致
    def rename_cfg_name(self):
        allfile = order_case.get_filepath(self)
        for i in range(len(allfile)):
            filename = allfile[i].split('\\')[-1]
            value = filename.split('.')[0]
            # print(value)
            with open(allfile[i], 'rb') as f:
                json_data = json.load(f)
                cfgdata = json_data[0]['config']['name']
                # print('old_name', cfgdata)
                if cfgdata != value:
                    json_data[0]['config']['name'] = value
                    print('new_name', json_data[0]['config']['name'])
                else:
                    continue
            f.close()
            if cfgdata != value:
                with open(allfile[i], 'w') as f:
                    json.dump(json_data, f, indent=4, separators=(',',' :'))
                f.close()
            else:
                continue



def run():
    d = os.path.dirname(__file__)
    parent_path = os.path.dirname(d)
    projectPath = os.path.dirname(parent_path)
    # dir = projectPath+'/testcases/basic_flow_2018_9_25'
    dir = 'F:\\python\\auto_test\\basic_flow_2018_9_25'
    print(dir)

    od = order_case(dir)
    # # 修改文件名和cfg name 的值一致
    # od.rename_file()
    # 获取原始的排序  letter代表字母排序，num代表数字排序
    # order_filename = od.get_allFile_order(type='letter')
    # # 文件名替换成数字
    # od.replace_index(order_filename)


    # # # 获取原始的排序  letter代表字母排序，num代表数字排序
    # order_filename = od.get_allFile_order(type='num')
    # # print(order_filename)
    # # # 替换成数字
    # od.replace_index(order_filename)

    # # # 测试排序
    old_files = od.get_allFile_order('num')
    print('old files',old_files)
    # 重新自动递增排列顺序
    new_files_order = update_list(old_files)
    print('old files',new_files_order)

    od.replace_index_byOrder(new_files_order)
    #
    # 修改cfg name 和 文件名保持一致
    od.rename_cfg_name()


if __name__ == '__main__':
    run()